package duan.http;

import com.google.gson.Gson;
import duan.constant.RespConstant;
import duan.exception.PlatformException;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Repository;

import javax.annotation.PostConstruct;
import java.nio.charset.StandardCharsets;

/**
 * HTTP调用类
 *
 * @author zhuyufeng
 */
@Repository
public class HttpConnUtil {

    // http连接池最大连接数
    private static final int maxTotal = 200;

    // 请求成功返回码
    private static final int SUCCESS_CODE = 200;

    // http路由连接数
    private static final int DefaultMaxPerRoute = 200;

    // 读数据超时时间
    private static final int READ_DATA_TIMEOUT = 3000;

    // 连接超时时间
    private static final int CONNECTION_TIMEOUT = 3000;

    PoolingHttpClientConnectionManager cm = null;

    // 请求超时设置
    private static final RequestConfig requestConfig = RequestConfig.custom().
            setConnectTimeout(CONNECTION_TIMEOUT).setSocketTimeout(READ_DATA_TIMEOUT).build();

    /**
     * 初始化连接池<同步>
     *  获取其中空闲连接
     * @return
     */
    @PostConstruct
    public void init() {
        ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory();
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", plainsf).build();
        cm = new PoolingHttpClientConnectionManager(registry);
        // 将最大连接数增加到200
        cm.setMaxTotal(maxTotal);
        // 将每个路由基础的连接增加到200
        cm.setDefaultMaxPerRoute(DefaultMaxPerRoute);
    }

    public CloseableHttpClient getHttpClient() {
        CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(cm).build();
        return httpclient;
    }

    /**
     * 初始化GET连接
     * @param url
     * @return
     */
    private HttpGet HttpGetConnect(String url) {
        HttpGet hget = new HttpGet(url);
        // 配置请求的超时设置
        hget.setConfig(requestConfig);
        return hget;
    }

    /**
     * 发送HTTP GET请求
     * @param url
     * @return
     */
    public String doGet(String url) {
        String result = "";
        CloseableHttpResponse response = null;
        HttpGet httpGet = HttpGetConnect(url);
        CloseableHttpClient httpclient = getHttpClient();
        httpGet.setHeader("HeaderEncode", "UTF-8");
        try {
            response = httpclient.execute(httpGet);
            if (response != null && response.getStatusLine().getStatusCode() == SUCCESS_CODE) {
                HttpEntity resEntity = response.getEntity();
                result = EntityUtils.toString(resEntity, StandardCharsets.UTF_8);
                EntityUtils.consume(resEntity);
            } else {
                throw new PlatformException(RespConstant.NETWORK_ERROR_MSG);
            }
            response.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            httpGet.releaseConnection();
        }
        return result;
    }

}
